package com.mornd.gulimall.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: mornd
 * @dateTime: 2023/8/31 - 13:51
 * 网关层面的流控响应callback
 */

@Configuration
public class SentinelGatewayConfig {

    public SentinelGatewayConfig() {
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("code", HttpStatus.TOO_MANY_REQUESTS.value()); // 429
                map.put("msg", HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
                String r = JSON.toJSONString(map);

                Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(r), String.class);
                return body;
            }
        });
    }
}
